#include "UdpServer.hpp"
#include "Comm.hpp"
#include <iostream>
#include <memory>
#include <cstdio>
using namespace std;

void Usage(std::string proc)// 提示说明
{
    cout << "Usage: \n\t" << proc << " local_port\n" << endl;
}


// bool SafeCheck(string& command)
// {
// }
string ExecuteCommand(string command)
{
    //if(!SafeCheck(command)) return "bad man!!!";
    cout << "get a message: " << command << endl;
    FILE* fp = popen(command.c_str(), "r");//打开一个进程（子程序）并建立一个管道（pipe）并读取命令
    if(fp == nullptr)
    {
        return "execute error, reason is unknown";
    }
    string response;
    char buffer[1024];
    while(1)
    {
        char* s = fgets(buffer, sizeof(buffer), fp);
        if(!s) break;
        else response += buffer;
    }
    pclose(fp);
    return response.empty() ? "success" : response;
}

const string OnMessageDefault(string request)
{
    // 命令执行
    return ExecuteCommand(request);;
}

int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        return Usage_Err;
    }
    //std::string ip = argv[1];
    uint16_t port = std::stoi(argv[1]);
    
    std::unique_ptr<UdpServer> usvr = std::make_unique<UdpServer>(OnMessageDefault, port);
    usvr->Init();
    usvr->Start();

    return 0;
}